# -*- coding: utf-8 -*-
# @Time    : 2025/2/22 16:55
# @Author  : me
# @File    : cv匹配2.py
# @Software: PyCharm
# @Action: :
import cv2
import numpy as np


def distance_cv(bg, tp):
    """
    :param slice_url: 滑块（缺口）图片地址
    :param bg_url: 背景图地址
    :return: distance
    :rtype:integer
    """
    slice_image = cv2.imread(tp)
    slice_image = cv2.Canny(slice_image, 255, 255)

    bg_image = cv2.imread(bg)
    bg_image = cv2.pyrMeanShiftFiltering(bg_image, 5, 50)
    bg_image = cv2.Canny(bg_image, 255, 255)

    result = cv2.matchTemplate(bg_image, slice_image, cv2.TM_CCOEFF_NORMED)

    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
    return max_loc[0]


def draw_img():
    # 创建一个 100x100 的白色图片
    # image = np.ones((100, 100, 3), dtype=np.uint8) * 255  # 白色是 (255, 255, 255)
    # image = np.zeros((100, 100, 3), dtype=np.uint8)  # 黑色是 (0, 0, 0)
    image = np.zeros((100, 100, 3), dtype=np.uint8)
    image[:, :, 0] = 255  # 将蓝色通道设置为 255  # 切片，取第几列  BGR
    print(image)
    # 保存图片
    cv2.imwrite('white_image.png', image)
    # 显示图片（可选）
    cv2.imshow('White Image', image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()


# 获取滑块距离
def identify_gap(bg, tp):
    """
    bg: 背景图片
    tp: 缺口图片
    out: 输出图片
    """
    # 读取背景图片和缺口图片
    bg_img = cv2.imread(bg)
    tp_img = cv2.imread(tp) # 缺口图片
    # tp_img = cv2.resize(tp_img, (100, 100))
    # print(bg_img)
    # print(tp_img)
    # yy = []
    # xx = []
    # for y in range(tp_img.shape[0]):
    #     for x in range(tp_img.shape[1]):
    #         r = tp_img[y, x]
    #         if r < 200:
    #             yy.append(y)
    #             xx.append(x)
    # tp_img = tp_img[min(yy):max(yy), min(xx):max(xx)]
    # 识别图片边缘
    bg_edge = cv2.Canny(bg_img, 100, 200)
    tp_edge = cv2.Canny(tp_img, 100, 200)
    # 转换图片格式
    bg_pic = cv2.cvtColor(bg_edge, cv2.COLOR_GRAY2RGB)
    tp_pic = cv2.cvtColor(tp_edge, cv2.COLOR_GRAY2RGB)
    # 缺口匹配
    res = cv2.matchTemplate(bg_pic, tp_pic, cv2.TM_CCOEFF_NORMED)
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)  # 寻找最优匹配
    # # 绘制方框
    th, tw = tp_pic.shape[:2]
    tl = max_loc  # 左上角点的坐标
    br = (tl[0] + tw, tl[1] + th)  # 右下角点的坐标
    cv2.rectangle(bg_img, tl, br, (0, 0, 255), 2)  # 绘制矩形
    cv2.imwrite('distinguish.jpg', bg_img)  # 保存在本地
    # 返回缺口的X坐标
    return max_loc[0]


def FindPic(target, template):
    """
    找出图像中最佳匹配位置
    :param target: 目标即背景图
    :param template: 模板即需要找到的图
    :return: 返回最佳匹配及其最差匹配和对应的坐标
    """
    target_rgb = cv2.imread(target)
    target_gray = cv2.cvtColor(target_rgb, cv2.COLOR_BGR2GRAY)
    template_rgb = cv2.imread(template, 0)
    res = cv2.matchTemplate(target_gray, template_rgb, cv2.TM_CCOEFF_NORMED)
    value = cv2.minMaxLoc(res)

if __name__ == '__main__':
    # draw_img()
    print(identify_gap('background.png', 'slider.png'))
    print(distance_cv('background.png', 'slider.png'))